import type { PropertyItem } from '@/services/develop/types';
import {
  addProperty,
  updateProperty,
  removeProperty,
  settingProperty,
} from '@/services/develop/property';
import { message } from 'antd';

/**
 * 添加属性
 *
 * @param fields
 */
export const handleAdd = async (fields: PropertyItem) => {
  const hide = message.loading('正在新增属性');

  try {
    await addProperty({ ...fields });
    hide();
    message.success('属性添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('属性添加失败，请重试！');
    return false;
  }
};

/**
 * 更新属性
 *
 * @param fields
 */
export const handleUpdate = async (fields: PropertyItem, currentRow?: PropertyItem) => {
  const hide = message.loading('正在更新属性');

  try {
    await updateProperty({
      ...currentRow,
      ...fields,
    });
    hide();
    message.success('属性更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('属性更新失败，请重试');
    return false;
  }
};

/**
 * 删除属性
 *
 * @param selectedRows
 */
export const handleRemove = async (selectedRows: PropertyItem[]) => {
  const hide = message.loading('正在删除属性');
  if (!selectedRows) return true;

  try {
    await removeProperty(selectedRows.map((row) => row.id));
    hide();
    message.success('属性删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('属性删除失败，请重试');
    return false;
  }
};

export const handleSetting = async (modelId: string, properties: PropertyItem[]) => {
  const hide = message.loading('正在保存属性设置');

  properties.forEach((p) => {
    if (p.validateLength == null || p.validateLength.length == 0) return;

    p.validateLengthMin = p.validateLength[0];
    p.validateLengthMax = p.validateLength[1];
    console.log('----done');
  });

  try {
    await settingProperty({
      modelId,
      properties,
    });
    hide();
    message.success('保存属性设置成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('保存属性设置失败，请重试');
    return false;
  }
};
